import React,{useEffect,useState} from 'react';
import { ActivityIndicator, StyleSheet,View,Text} from 'react-native';
import Events from './event';
import {size} from '@/app/utils';

let ToastLoading = ()=>{

    let [loading,setLoading] = useState(false);
    let [dotCount,setDotCount] = useState(0);
    let [loadingText,setLoadingText] = useState('loading');
    useEffect(()=>{
        Events.addListener("loading",_loading)
    },[])

    const _loading = (bl: boolean, title: string = 'loading') => {
        console.log('title-------:',title);
        setLoadingText(title);
        setLoading(bl);
    }

    useEffect(()=>{
        const timer = setInterval(()=>{
            setDotCount(prev => (prev + 1) % 4);
        },500)
        return ()=>clearInterval(timer)
    },[])

    return (
        loading?<View style={[styles.loading,{zIndex: loading ? 10 : -1}]}>
            <View style={styles.loadingbox}>
                <ActivityIndicator size="large" color="#ffffff" />
                <Text style={styles.loadText}>
                    {loadingText}
                    {Array.from({length:3}).map((_, i) => (
                        <Text key={`dot-${i}`} style={{color: i < dotCount ? '#ffffff' : 'rgba(255,255,255,0)'}}>.</Text>
                    ))}
                </Text>
            </View>
        </View>:null
    )
}

const styles = StyleSheet.create({
    loading: {
        position: "absolute",
        left: 0,
        top: 0,
        right: 0,
        bottom: 0,
        zIndex: 999,
        elevation: 999,
        backgroundColor: "rgba(0,0,0,0)",
        flexDirection:'column',
        alignItems:'center',
        justifyContent:'center'
    },
    loadingbox:{
        backgroundColor: "rgba(0,0,0,0.6)",
        width:size(120),
        height:size(120),
        flexDirection:'column',
        alignItems:'center',
        justifyContent:'center',
        borderRadius:size(6),
    },
    loadText:{
        color:'#ffffff',
        fontSize:size(14),
        marginTop:size(10)
    }
})

export default ToastLoading;